package com.wedo.mall.widget;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.e.library.activity.EActivity;
import com.e.library.listener.EListener;
import com.wedo.mall.R;
import com.wedo.mall.adapter.HistoryAdapter;
import com.wedo.mall.db.DBHelper;
import com.wedo.mall.entity.History;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;

/**
 * 搜索控件，含有历史记录
 * @author lxy
 * @time 2017/7/24  17:27
 */
public class SearchView extends LinearLayout {

    @BindView(R.id.iv_clear) ImageView iv_clear;
    @BindView(R.id.et_search) EditText et_search;
    @BindView(R.id.rv_history) RecyclerView rv_history;
    @BindView(R.id.ll_history)  LinearLayout ll_history;
    private HistoryAdapter mHistoryAdapter;

    public SearchView(Context context) {
        this(context,null);
    }

    public SearchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public SearchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        setOrientation(VERTICAL);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        this.addView(LayoutInflater.from(context).inflate(R.layout.layout_search,null),params);
        ButterKnife.bind(this);

        et_search.setFocusable(true);

        rv_history.setHasFixedSize(false);
        rv_history.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));
        mHistoryAdapter = new HistoryAdapter(context,new ArrayList<History>());
        rv_history.setAdapter(mHistoryAdapter);
        mHistoryAdapter.setItemClickListener(new EListener<History>() {
            @Override
            public void onInvoked(View view, History data, int position) {
                et_search.setText(data.keyword);
                search(data.keyword);
            }
        });

        ll_history.setVisibility(View.GONE);
    }

    public void requestPermission(Activity activity){
        if(ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }

    public void onRequestPermissionsResult(EActivity activity,int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == 1) {
            if(grantResults.length == 0) {
                activity.toast("请同意权限再操作");
                activity.defaultFinish();
            }
        }
    }

    @OnClick(R.id.btn_cancel)
    protected void onCancelClick(){
        Context context = getContext();
        if(context instanceof EActivity) {
            ((EActivity) context).defaultFinish();
        }else if(context instanceof Activity) {
            ((Activity) context).finish();
        }
    }

    @OnClick(R.id.et_search)
    protected void onSearchClick(){
        if(ll_history.isShown()) {
            return;
        }
        ll_history.setVisibility(View.VISIBLE);
        List<History> histories = DBHelper.with(getContext()).histories();
        mHistoryAdapter.refresh(histories);
    }

    @OnTextChanged(R.id.et_search)
    protected void onTextChanged(Editable editable){
        String input = editable.toString();
        iv_clear.setVisibility(!TextUtils.isEmpty(input)?VISIBLE:GONE);
    }

    @OnClick(R.id.iv_clear)
    protected void onClearClick(){
        et_search.setText("");
    }

    @OnClick(R.id.ll_history)
    protected void onHistoryClick(){
        ll_history.setVisibility(View.GONE);
    }

    @OnEditorAction(R.id.et_search)
    protected boolean onSearchAction(int action){
        if (action == EditorInfo.IME_ACTION_SEARCH || action == EditorInfo.IME_ACTION_UNSPECIFIED){
            String keyword = et_search.getText().toString();
            search(keyword);
            return true;
        }
        return false;
    }

    private void search(String keyword){
        if (TextUtils.isEmpty(keyword)){
            return;
        }

        hideHistory();
        DBHelper.with(getContext()).insert(keyword);
        if(listener !=null) {
            listener.search(keyword);
        }
    }

    public void hideHistory(){
        et_search.clearFocus();
        ll_history.setVisibility(View.GONE);
    }

    public SearchView listener(SearchListener listener){
        this.listener = listener;
        return this;
    }

    private SearchListener listener;
    public interface SearchListener{
        void search(String keyword);
    }
}
